# 爬取有道翻译
from urllib import request,parse
import requests
import json
import time
import random
import hashlib

# md5加密
def getMD5(val):
    md5=hashlib.md5()
    md5.update(bytes(val,encoding='utf-8'))
    sign=md5.hexdigest()
    return sign

# 生成请求参数
def getParams(keyword):
    param={"salt":"","sign":"","ts":"","bv":""}
    # 生成ts
    ts = int(time.time())
    # 生成bv
    bv = getMD5('Mozilla/4.0 ')
    # 生成salt
    salt = ts + random.randint(0, 10)
    # 生成sign
    sign = "fanyideskweb" + keyword + str(salt) + "p09@Bn{h02_BIEe]$P^nG"
    sign = getMD5(sign)
    param = {"salt": salt, "sign": sign, "ts": ts, "bv": bv}
    return param

# 使用urllib爬取
def fanyi_urllib(keyword):
    # 定义请求地址及参数
    url="http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
    params=getParams(keyword)
    data = {
        "i": keyword,
        'from': "AUTO",
        'to': "AUTO",
        'smartresult': "dict",
        'client': "fanyideskweb",
        'salt': params["salt"],
        'sign': params["sign"],
        'ts': params["ts"],
        'bv': params["bv"],
        'doctype': "json",
        'version': "2.1",
        'keyfrom': "fanyi.web",
        'action': 'FY_BY_REALTIME',
        'typoResult': 'false'
    }
    # 参数编码
    data=parse.urlencode(data)
    # 设置header头
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        # "Accept-Encoding":"gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Connection": "keep-alive",
        "Content-Length": len(data),
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Cookie": "OUTFOX_SEARCH_USER_ID=-1911965012@10.168.8.61; JSESSIONID=aaaDpB6WepRgUcAMNzDEw; OUTFOX_SEARCH_USER_ID_NCOO=1856585262.9897783; ___rl__test__cookies=1544537308310",
        "Host": "fanyi.youdao.com",
        "Origin": "http://fanyi.youdao.com",
        "Referer": "http://fanyi.youdao.com/?keyfrom=fanyi.logo",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }
    # 发送请求 爬取信息
    try:
        req=request.Request(url,data=bytes(data,encoding='utf-8'),headers=headers)
        res=request.urlopen(req)
        #解析
        str_json=res.read().decode('utf-8',"ignore")
        rlt=json.loads(str_json)
        if "smartResult" in rlt:
            print(rlt["smartResult"]["entries"])
        else:
            print("解析错误!")
    except Exception as err:
        print("解析错误")

# 使用requests爬取
def fanyi_request(keyword):
    #请求地址及参数
    url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
    params = getParams(keyword)
    data = {
        "i": keyword,
        'from': "AUTO",
        'to': "AUTO",
        'smartresult': "dict",
        'client': "fanyideskweb",
        'salt': params["salt"],
        'sign': params["sign"],
        'ts': params["ts"],
        'bv': params["bv"],
        'doctype': "json",
        'version': "2.1",
        'keyfrom': "fanyi.web",
        'action': 'FY_BY_REALTIME',
        'typoResult': 'false'
    }
    # 设置header头
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        # "Accept-Encoding":"gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Connection": "keep-alive",
        # "Content-Length": len(data),
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Cookie": "OUTFOX_SEARCH_USER_ID=-1911965012@10.168.8.61; JSESSIONID=aaaDpB6WepRgUcAMNzDEw; OUTFOX_SEARCH_USER_ID_NCOO=1856585262.9897783; ___rl__test__cookies=1544537308310",
        "Host": "fanyi.youdao.com",
        "Origin": "http://fanyi.youdao.com",
        "Referer": "http://fanyi.youdao.com/?keyfrom=fanyi.logo",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }
    #发送请求，爬取信息
    try:
        res=requests.post(url,data=data,headers=headers)
        # 解析
        str_json=res.content.decode("utf-8")
        # print(str_json)
        rlt=json.loads(str_json)
        if "smartResult" in rlt:
            print(rlt["smartResult"]["entries"])
        else:
            print("解析错误!")
    except Exception as err:
        print("解析异常！")

if __name__=="__main__":
    while True:
        kw=input("请输入要翻译的词：")
        if kw=="q":# 输入q结束
            break
        # 使用urllib爬取
        # fanyi_urllib(kw)

        # 使用requests爬取
        fanyi_request(kw)